<!--
 * @Author: LAB
 * @Date: 2021-05-18 11:40:44
 * @Description: 药品基础信息
 * @FilePath: \client-app\src\views\storeroom\components\drug-length-base.vue
-->
<template>
  <DxDataGrid
    v-bind="DataGridSetting"
    :dataSource="dataSource"
    @context-menu-preparing="
      e => {
        (rightContextOption.content = { event: e, id: 'drugBase' }),
          (rightContextOption.items = rightMenu);
      }
    "
    :remote-operations="false"
  >
    <template #uploadImg="{ data: cellInfo }">
      <imageUpload
        :limit="1"
        :files="cellInfo.Value"
        @change="cellInfo.setValue"
      />
    </template>
    <template #headerTemplate="{ data: column }">
      <div class="header-input" style="width: 100%">
        <div
          style="width: 60%"
          v-if="!isEditHeader[column.columnIndex]"
          @dblclick="isEditHeader[column.columnIndex] = true"
          @click.stop="none"
        >
          {{ getHeaderTitle(column) }}
        </div>
        <DxTextBox
          @keydown.stop="none"
          @click.stop="none"
          v-else
          :placeholder="column.column.caption"
          :Value="getHeaderTitle(column)"
          @focusOut="
            event => setHeader(event, column.column, column.columnIndex)
          "
          @enterKey="
            event => setHeader(event, column.column, column.columnIndex)
          "
        />
      </div>
    </template>
  </DxDataGrid>
  <Pagination v-model:page="pageInfo" @update:page="setPageToUtl"></Pagination>
  <DxPopup
    v-model:visible="isImport"
    :show-title="true"
    title="导入数据"
    :width="400"
    :height="400"
    @change="getFile"
  >
    <p style="color: #999; margin: 10px 0">导入数据到</p>
    <p style="color: #333; font-size: 18px; margin: 10px 0">
      {{ catalogName }} - {{ displayId }}
    </p>
    <imageUpload
      :files="[]"
      :allowedFileExtensions="['.xlsx', '.xls']"
      :limit="1"
      @change="getFile"
    />
    <p style="color: #999; margin: 10px 0">请上传需要导入数据文件</p>
    <div class="lb-form-button">
      <DxButton
        :width="120"
        text="保存"
        type="default"
        styling-mode="text"
        @click="uploadXlsx"
      />
      <DxButton
        :width="120"
        text="取消"
        type="default"
        styling-mode="text"
        @click="isImport = false"
      />
    </div>
  </DxPopup>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import ImageUpload from "@/components/image-upload.vue";
import { ApiTool } from "@/api/api-tool";
import { Inject, Watch } from "vue-property-decorator";
import {
  DictionaryClient,
} from "@/api/api_dictionaryclient";
import DataSource from "devextreme/data/data_source";
import notify from "devextreme/ui/notify";
import { DxHtmlEditor } from "devextreme-vue/html-editor";
import Pagination from "@/framework/elementui/pagination.vue";
import DxTabs from "devextreme-vue/tabs";
import {
  DxDataGrid,
  DxColumn,
  DxPaging,
  DxEditing,
  DxLookup,
  DxForm,
  DxSearchPanel,
  DxExport,
  DxSorting,
  DxPager,
  DxRequiredRule,
  DxEmailRule,
  DxPatternRule,
  DxAsyncRule,
  DxSelection
} from "devextreme-vue/data-grid";
import { DxPopup } from "devextreme-vue/popup";
import DxButton from "devextreme-vue/button";
import { SearchByURL } from "@/utils/search-byurl";
import { RouteLocation } from "vue-router";
import { PageInfo, Tool } from "@/utils/tool";
import { ApiExceptionShow } from "@/utils/api-exception-show";
import DxTextBox from "devextreme-vue/text-box";
import ThemeSwitch from "@/framework/theme-switch/theme-switch";
import { DictionaryFieldOutput } from "@/api/api_solutionclient";
import { CatalogClient } from "@/api/api_catalogclient";
import { ViewTool } from "@/framework/utils/view-tool";
import DxSortable from "devextreme-vue/sortable";
import LoadElement from "@/framework/utils/load-element";
import Tree from "@/framework/components/tree/tree.vue";
import { RightContextI } from "@/framework/components/right-menu/right-menu.vue";
// import CreateMiddle from "./create-middle.vue";
const componentInfo = {
  title: "药品信息"
};
const dataSourceKey = "dictionaryId";
let formData: any = {};
let self: any;
// 配置类型 1：金融中心产品轮播图 2：金融产品类型配置 3：还款方式 4 协议配置
const getDataGridSetting = function() {
  return {
    height: "calc(100vh - 150px)",
    // width: "calc(100vw - 355px)",
    showBorders: true,
    showColumnLines: true,
    showRowLines: true,
    hoverStateEnabled: true,
    allowColumnResizing: true,
    allowColumnReordering: true,

    sorting: {
      mode: "single"
    },
    rowAlternationEnabled: true,
    noDataText: "暂无数据列表",
    onToolbarPreparing: e => {
      let toolbarItems = e.toolbarOptions.items;
      toolbarItems.length = 0;
    },
    columns: [
      {
        caption: "id",
        dataField: "dictionaryId",
        fixed: true,
        allowEditing: false,
        allowSorting: false,
        width: 160
      },
      {
        caption: "编码 ",
        dataField: "value1",
        width: 160,
        fixed: true
      },
      {
        caption: "药品品种",
        dataField: "value2",
        width: 160
      },
      {
        caption: "商品名",
        dataField: "value3",
        width: 160
      },
      {
        caption: "规格",
        dataField: "value4",
        width: 160
      },
      {
        caption: "厂牌",
        dataField: "value5",
        width: 160
      },
      {
        caption: "单位",
        dataField: "value6",
        width: 160
      },
      {
        caption: "零售价",
        dataField: "value7",
        width: 160
      },
      {
        caption: "库存数量",
        dataField: "value8",
        width: 160
      },
      {
        caption: "允许领用",
        dataField: "value",
        width: 160
      },
      {
        caption: "储备上限",
        dataField: "value10",
        width: 160
      },
      {
        caption: "储备下限",
        dataField: "value11",
        width: 160
      },
      {
        caption: "日盘",
        dataField: "value12",
        width: 160
      },
      {
        caption: "周盘",
        dataField: "value13",
        width: 160
      },
      {
        caption: "月盘",
        dataField: "value14",
        width: 160
      },
      {
        caption: "季盘",
        dataField: "value15",
        width: 160
      },
      {
        caption: "货位",
        dataField: "value16",
        width: 160
      }
    ],
    editing: {
      allowAdding: true,
      allowDeleting: true,
      allowUpdating: true,
      mode: "cell"
    },
    export: {
      enabled: true,
      allowExportSelectedData: true,
      fileName: componentInfo.title + new Date()
    },
    onEditingStart(item) {
      formData = item.data;
    }
  };
};

@Options({
  components: {
    DxDataGrid,
    DxColumn,
    DxPaging,
    DxEditing,
    DxPopup,
    DxLookup,
    DxForm,
    DxSearchPanel,
    DxExport,
    DxSorting,
    DxPager,
    DxRequiredRule,
    DxEmailRule,
    DxPatternRule,
    DxAsyncRule,
    DxSelection,
    ImageUpload,
    DxHtmlEditor,
    Pagination,
    DxTextBox,
    DxButton,
    DxSortable,
    Tree,
    DxTabs,
    // CreateMiddle
  }
})
export default class DrugLengthBase extends Vue {
  @Inject()
  apiTool: ApiTool;
  importFile: any = {};
  formData: any;
  searchByURL: SearchByURL;
  pageInfo: PageInfo = {
    count: 0,
    index: 1,
    pageSize: 15,
    pageCount: 0
  };
  openTab = 0;
  isImport = false;
  solutionId = "";
  catalogId = "";
  catalogName = "";
  displayId = "";
  isEditHeader: Array<boolean> = [];
  headerNameList: Map<string, DictionaryFieldOutput> = new Map();
  @Inject()
  rightContextOption: RightContextI;

  rightMenu = [
    {
      text: "新增",
      id: "add"
    },
    {
      id: "edit",
      text: "修改"
    },
    {
      id: "print",
      text: "打印"
    },
    {
      id: "import",
      text: "导入"
    },
    {
      id: "enable",
      text: "启用"
    },
    {
      id: "disable",
      text: "禁用"
    },
    {
      text: "显示",
      id: "show",
      items: [
        {
          id: "showDurgNum",
          text: "药品数量"
        },
        {
          id: "showSku",
          text: "规格数量"
        },
        {
          id: "showAbled",
          text: "启用"
        },
        {
          id: "showDisabled",
          text: "停用"
        }
      ]
    }
  ];
  treeData = [
    {
      id: "A",
      parentid: "1",
      name: "測試",
      items: [
        {
          id: "2",
          parentid: "1",
          name: "測試1",
          items: []
        },
        {
          id: "3",
          parentid: "1",
          name: "測試1",
          items: []
        },
        {
          id: "4",
          parentid: "1",
          name: "測試1",
          items: []
        }
      ]
    },
    {
      id: "B",
      parentid: "",
      name: "測試",
      items: [
        {
          id: "B2",
          parentid: "A",
          name: "測試1",
          items: []
        },
        {
          id: "B3",
          parentid: "A",
          name: "測試1",
          items: []
        },
        {
          id: "B4",
          parentid: "A",
          name: "測試1",
          items: []
        }
      ]
    }
  ];

  @Watch("$route.query")
  watchQuery(newVal, oldVal) {
    // if (Tool.sameRoute(newVal, oldVal)) return;
    this.getUrlquery(newVal);
    this.dataSource.reload();
  }
  DataGridSetting = getDataGridSetting.call(this);
  dataSource = new DataSource({});
  // 从url上获取参数
  getUrlquery(newVal: any) {
    this.pageInfo.index = 0;
    this.isEditHeader = [];
    this.solutionId = (newVal.solutionId || "").toString();
    this.catalogId = (newVal.catalogId || "").toString();
    this.catalogName = Tool.convertToString(newVal["name"]);
    this.displayId = Tool.convertToString(newVal["displayId"]);
    this.pageInfo.index = Tool.convertToNumber((newVal.page || "").toString());
  }
  // 拖动结束
  onDragEnd(e) {
    // 无效拖动
    if (e.toData == "listData") {
      return;
    }
    let dataKey = "item";
    let fromIndex = e.itemElement.rowIndex;
    let toIndex = e.toIndex;
    let items = this.dataSource.items();
    let fromItem = items[fromIndex];
    let treeNodes = LoadElement.selectElementAll(".tree-node-item");
    let toItem = JSON.parse(treeNodes[toIndex].dataset[dataKey]);
    let { catalogId } = toItem;
    // 无效拖动
    if (catalogId == fromItem.catalogId) {
      return;
    }
    let editItem = Object.assign(fromItem, { catalogId });
    let client = this.apiTool.createClient(DictionaryClient);
  }
  rightClick(event: CustomEvent) {
    let { detail = {} } = event;
    let itemData = detail.event.itemData;
    let content = detail.content;
    if (content.id != "drugBase") {
      return;
    }
    switch (itemData.id) {
      case "add":
        break;

      default:
        break;
    }
  }
  beforeUnmount() {
    document.removeEventListener("rightContext", this.rightClick);
  }
  async mounted() {
    document.addEventListener("rightContext", this.rightClick);
    let newVal = this.$route.query;
    this.getUrlquery(newVal);
    this.searchByURL = new SearchByURL(this.$router, 0);
    self = this as any;
    let client = this.apiTool.createClient(DictionaryClient);
    
  }
  
  
  setPageToUtl() {
    this.searchByURL.setParamsToUrl({ page: this.pageInfo.index });
  }
  
  // 获取表格标题
  getHeaderTitle(column, headerNameList = this.headerNameList): string {
    let dataField = column.column.dataField.replace("v", "V");
    let caption = column.column.caption;
    let title = headerNameList.get(dataField);
    return title ? title.name : caption;
  }
  // 获取上传文件
  getFile(file) {
    this.importFile = file;
  }
  // 提交
  uploadXlsx() {
    let client = this.apiTool.createClient(CatalogClient);
    let catalogId = this.catalogId;
    let solutionId = this.solutionId;
    let tempFileInfo = this.importFile[0];
    if (!catalogId) {
      notify("请选择需要导入数据的目录");
      return;
    }
    ViewTool.showLoading(true, this);
    client
      .importCatalog({
        catalogId,
        solutionId,
        tempFileInfo
      })
      .then(result => {
        if (result.isSuccess) {
          notify("导入完成", "success", 2000);
          setTimeout(() => {
            this.refresh();
          }, 1000);
        } else {
          notify(result.message, "error", 2000);
        }
        ViewTool.showLoading(false, this);
      })
      .catch(e => {
        notify("系统异常", "error", 2000);
        ViewTool.showLoading(false, this);
      });
  }
  // 页面刷新
  refresh() {
    this.$router.replace({ path: "/refresh" });
  }
}
</script>

<style scoped lang="scss">
.grup-body {
  display: flex;
  justify-content: space-evenly;
}
.header-input {
  input {
    padding: 0 !important;
  }
}
</style>
